<?php

namespace App\Admin\Controllers;

use Illuminate\Http\Request;
use App\AdminUser;
use App\AdminRole;

class UserController extends Controller
{
	//首页
    public function index()
    {
    	$users = AdminUser::paginate(10);
        return view('/admin/user/index',compact('users'));
    }

    //增加页面
    public function add()
    {
        return view('/admin/user/add');
    }

    //首页
    public function store()
    {
    	//验证
    	$this->validate(request(),[
    		'name' => 'required|string|max:100|min:2|unique:admin_users,name',
    		'password' => 'required|string|min:3'
    	]);
    	//逻辑
    	$name = request('name');
    	$password = bcrypt(request('password'));
    	$user = AdminUser::create(compact('name', 'password'));
    	//渲染
        return redirect('/admin/users');
    }

    //用户角色页面
    public function role(AdminUser $user){
        $roles = AdminRole::all();
        $myRoles = $user->roles;
        return view('/admin/user/role',compact('roles', 'user', 'myRoles'));
    }

    //储存角色页面
    public function storeRole(AdminUser $user){
        //验证
        $this->validate(request(),[
            'roles' => 'required|array'
        ]);
        //逻辑
        $roles = AdminRole::findMany(request('roles'));
        $myRoles = $user->roles;

        //要增加的
        $addRoles = $roles->diff($myRoles);
        foreach ($addRoles as $role) {
            $user->assignRole($role);
        }

        //要增加的
        $deleteRoles = $myRoles->diff($roles);
        foreach ($deleteRoles as $role) {
            $user->deleteRole($role);
        }

        //渲染
        return back();
    }
}
